<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" placeholder="请输入" />
    <button class="btn1">点我发送</button>
    <button class="btn2">关闭连接</button>
    <div class="content"></div>
    <script>
      let content = document.querySelector('.content')
      // 1.创建ws连接
      const ws = new WebSocket('wss://echo.websocket.org')

      // 2.注册连接成功回调
      ws.onopen = function () {
        content.innerHTML += '<p style="color:red">服务器连接成功</p>'
      }

      // 3.主动给服务器发数据
      document.querySelector('.btn1').onclick = function () {
        let str = document.querySelector('input').value
        content.innerHTML += `<p>用户：${str}</p>`
        ws.send(str)
      }

      // 4.接收服务器数据
      ws.onmessage = function (data) {
        console.log(data)
        content.innerHTML += `<p>服务器：${data.data}</p>`
      }

      // 5.关闭连接
      document.querySelector('.btn2').onclick = function () {
        ws.close()
        content.innerHTML += '<p style="color:red">服务器关闭连接</p>'
      }
    </script>
  </body>
</html>
